<template>
  <div class="profile-container">
    <el-card class="header-card">
      <h2><el-icon><User /></el-icon> 管理员个人信息</h2>
    </el-card>

    <el-card v-loading="loading">
      <el-form :model="userForm" label-width="100px" class="profile-form">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userForm.nickname" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" disabled />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phonenumber" disabled />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userForm.sex" disabled>
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-tag type="danger">
            管理员
          </el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ formatTime(userForm.createTime) }}</span>
        </el-form-item>
        <el-form-item label="更新时间">
          <span>{{ formatTime(userForm.updateTime) }}</span>
        </el-form-item>
      </el-form>

      <div class="profile-actions">
        <el-button type="primary" :icon="Edit" @click="showEditDialog = true">
          编辑信息
        </el-button>
        <el-button type="warning" :icon="Key" @click="showChangePasswordDialog = true">
          修改密码
        </el-button>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人信息"
      width="500px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="editForm.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile" :loading="submitting">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showChangePasswordDialog"
      title="修改密码"
      width="500px"
      @close="resetPasswordForm"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangePasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="passwordSubmitting">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { User, Edit, Key } from '@element-plus/icons-vue';
import { getUserById, updateUser, changePassword, verifyUserPassword } from '@/api/user';
import { useUserStore } from '@/stores/user';
import type { User as UserType } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const router = useRouter();

const loading = ref(false);
const showEditDialog = ref(false);
const showChangePasswordDialog = ref(false);
const submitting = ref(false);
const passwordSubmitting = ref(false);
const editFormRef = ref<FormInstance>();
const passwordFormRef = ref<FormInstance>();

const userForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phonenumber: '',
  sex: '2' as '0' | '1' | '2',
  userType: '0' as '0' | '1',
  createTime: '',
  updateTime: ''
});

const editForm = reactive({
  nickname: '',
  email: '',
  phonenumber: '',
  sex: '2' as '0' | '1' | '2'
});

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const editRules: FormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 加载用户信息
const loadUserInfo = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const response = await getUserById(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      const user = response.data;
      userForm.username = user.username;
      userForm.nickname = user.nickname;
      userForm.email = user.email || '';
      userForm.phonenumber = user.phonenumber || '';
      userForm.sex = user.sex || '2';
      userForm.userType = user.userType || '0';
      userForm.createTime = user.createTime || '';
      userForm.updateTime = user.updateTime || '';
      
      // 初始化编辑表单
      editForm.nickname = user.nickname;
      editForm.email = user.email || '';
      editForm.phonenumber = user.phonenumber || '';
      editForm.sex = user.sex || '2';
    } else {
      ElMessage.error('加载用户信息失败');
    }
  } catch (error) {
    ElMessage.error('加载用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!editFormRef.value || !userStore.userId) return;
  
  await editFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    try {
      const response = await updateUser(userStore.userId!, {
        ...userStore.user!,
        nickname: editForm.nickname,
        email: editForm.email,
        phonenumber: editForm.phonenumber,
        sex: editForm.sex
      });

      if (response.operateResult === 'SUCC') {
        ElMessage.success('更新成功');
        showEditDialog.value = false;
        
        // 更新store中的用户信息
        const userRes = await getUserById(userStore.userId!);
        if (userRes.operateResult === 'SUCC' && userRes.data) {
          userStore.updateUserInfo(userRes.data);
        }
        
        await loadUserInfo();
      } else {
        ElMessage.error(response.errorMsg || '更新失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '更新失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value || !userStore.userId) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    if (!userStore.user?.username) {
      ElMessage.warning('请先登录');
      return;
    }

    passwordSubmitting.value = true;
    try {
      // 首先验证旧密码（使用和登录一样的验证接口）
      const verifyResponse = await verifyUserPassword(
        userStore.user.username,
        passwordForm.oldPassword
      );

      if (verifyResponse.operateResult !== 'SUCC') {
        ElMessage.error(verifyResponse.errorMsg || '旧密码验证失败');
        return;
      }

      // 旧密码验证通过后，修改密码
      const response = await changePassword(
        userStore.userId!,
        passwordForm.oldPassword,
        passwordForm.newPassword
      );

      if (response.operateResult === 'SUCC') {
        ElMessage.success('密码修改成功，请重新登录');
        showChangePasswordDialog.value = false;
        resetPasswordForm();
        
        // 延迟跳转到登录页面，让用户看到成功消息
        setTimeout(() => {
          userStore.logout();
          router.push('/login');
        }, 1500);
      } else {
        ElMessage.error(response.errorMsg || '密码修改失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '密码修改失败');
    } finally {
      passwordSubmitting.value = false;
    }
  });
};

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields();
  editForm.nickname = userForm.nickname;
  editForm.email = userForm.email;
  editForm.phonenumber = userForm.phonenumber;
  editForm.sex = userForm.sex;
};

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields();
  passwordForm.oldPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '未知';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.profile-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.profile-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px 0;
}

.profile-actions {
  text-align: center;
  margin-top: 30px;
  display: flex;
  gap: 15px;
  justify-content: center;
}
</style>
